//
//  UnityCapture.m
//  UnityCapture
//
//  Created by Adrian on 24.10.09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "UnityCapture.h"
#import "FrameMovieExporter.h"
#import "FrameReader.h"
#import "Queue.h"
#import "QueueController.h"
#import "UnityCaptureCore.h"

#import <OpenGL/OpenGL.h>

static UnityCaptureCore *core;

static CaptureHasStarted startCallback;
static CaptureHasEnded endCallback;
static ChangeResolution resolutionCallback;

static int playerWidth, playerHeight;

void StartUnityCapture(BOOL openWindow) {
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	
	if (!core) {
		core = [[UnityCaptureCore alloc] initWithOpenWindow:openWindow];
		
		if (playerWidth > 0)
			PassResolutionToCore();
	
	} else if (openWindow)
		[core openHelperWindow];
	
	[pool release];
}

void PassResolutionToCore() {
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	
	CGLContextObj cgl_ctx = CGLGetCurrentContext();
	if (!cgl_ctx) {
		NSLog(@"Failed to get OpenGL context from Unity.");
		return;
	}
	
	[core setCGLContext:cgl_ctx withWidth:playerWidth andHeight:playerHeight];
	
	[pool release];
}

void ResolutionDidChange(int width, int height) {
	
	playerWidth = width;
	playerHeight = height;
	
	if (core)
		PassResolutionToCore();
}

void CaptureFrame(float frameTime) {
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	
	[core captureFrame:frameTime];
	
	[pool release];
}

void StartStopCapture() {
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	
	[core toggleCapture];
	
	[pool release];
}

void RegisterCaptureStartCallback(CaptureHasStarted fp) {
	startCallback = fp;
}

void CaptureStartNotification(int framerate) {
	if (startCallback)
		startCallback(framerate);
}

void RegisterCaptureEndCallback(CaptureHasEnded fp) {
	endCallback = fp;
}

void CaptureEndNotification() {
	if (endCallback)
		endCallback();
}

void RegisterChangeResolutionCallback(ChangeResolution fp) {
	resolutionCallback = fp;
}

void ChangeResolutionNotification(int width, int height) {
	if (resolutionCallback)
		resolutionCallback(width, height);
}

void CleanUp() {
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	
	[core release];
	
	[pool release];
}